package com.example.administrator.bluetooth_data_transmission;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.RequiresApi;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.example.administrator.bluetooth_data_transmission.bean.DeepDataBean;
import com.example.administrator.bluetooth_data_transmission.bean.ReadDataBean;
import com.example.administrator.bluetooth_data_transmission.util.DigitalTrans;
import com.example.administrator.bluetooth_data_transmission.util.SaveToExcelUtil;
import com.example.administrator.bluetooth_data_transmission.util.ToastUtil;
import com.orhanobut.hawk.Hawk;

import org.w3c.dom.Text;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;

import cn.com.heaton.blelibrary.ble.Ble;
import cn.com.heaton.blelibrary.ble.BleDevice;

import static com.example.administrator.bluetooth_data_transmission.util.GetDir.getExcelDir;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private Button btnSure, btnTime, btnDeep, btnRead, btnFit, btnRecover, btnEndTime;
    private EditText etName, etDeep, etTime;
    private ImageView iv_search;
    private Ble<BleDevice> mBle;
    private Timer timer;
    private List<DeepDataBean> list = new ArrayList<>();
    private String startTime = "";
    private String randomStr;
    private boolean isStart = false;
    private SaveToExcelUtil saveToExcelUtil;
    private File file1;
    private String endTime;
    List<ReadDataBean> data = new ArrayList<>();
    private List<String> deepTime=new ArrayList<>();
    private boolean isFile=false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_main);
        mBle = Ble.getInstance();
        initViews();
        initListener();
    }

    private void initListener() {
        iv_search.setOnClickListener(this);
        btnSure.setOnClickListener(this);
        btnTime.setOnClickListener(this);
        btnDeep.setOnClickListener(this);
        btnRead.setOnClickListener(this);
        btnFit.setOnClickListener(this);
        btnRecover.setOnClickListener(this);
        btnEndTime.setOnClickListener(this);
    }

    private void initViews() {
        btnSure = findViewById(R.id.btn_sure);
        btnTime = findViewById(R.id.btn_time);
        btnDeep = findViewById(R.id.btn_deep);
        btnRead = findViewById(R.id.btn_data_read);
        btnFit = findViewById(R.id.btn_fitting);
        btnRecover = findViewById(R.id.btn_recovery);
        etName = findViewById(R.id.et_name);
        etDeep = findViewById(R.id.et_deep);
        etTime = findViewById(R.id.et_time);
        iv_search = findViewById(R.id.iv_search);
        btnEndTime = findViewById(R.id.btn__end_time);
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE},
                    1);
        } else {

        }
    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_sure:
                if (TextUtils.isEmpty(etName.getText().toString())) {
                    ToastUtil.showToast("文件夹名不能为空");
                    return;
                }
                if (etName.getText().toString() != null) {
                    randomStr = Environment.getExternalStorageDirectory().toString() + File.separator + etName.getText().toString() + File.separator + new Random().nextInt(100) + ".xls";
                }
                File file = new File(Environment.getExternalStorageDirectory(), etName.getText().toString());
                if (!file.exists()) {
                    file.mkdir();
                    isFile=true;
                    ToastUtil.showToast("创建成功");
                }else {
                    ToastUtil.showToast("文件夹已经存在");
                    isFile=true;
                }
                break;
            //开始时间同步
            case R.id.btn_time:
                isStart = true;
                 if(isFile){
                     saveToExcelUtil = new SaveToExcelUtil(this, randomStr);
                     startTime = DigitalTrans.getTime();
                     btnTime.setVisibility(View.GONE);
                     btnEndTime.setVisibility(View.VISIBLE);
                     timer = new Timer();
                     timer.schedule(new TimerTask() {
                         @Override
                         public void run() {
                             runOnUiThread(new Runnable() {
                                 @RequiresApi(api = Build.VERSION_CODES.N)
                                 @Override
                                 public void run() {
                                     etTime.setText(DigitalTrans.getTime());
                                 }
                             });

                         }
                     }, 0, 1000);
                 }
               else {
                     ToastUtil.showToast("请先创建文件夹");
                 }
                break;
            //结束时间同步
            case R.id.btn__end_time:
                endTime = etTime.getText().toString().trim();
                isStart = false;
                btnTime.setVisibility(View.VISIBLE);
                btnEndTime.setVisibility(View.GONE);
                timer.cancel();
                if (Hawk.get("READDATA") != null && Hawk.get("BLEDATA") == null) {
                    for (int i = 0; i < list.size(); i++) {
                        DeepDataBean bean = list.get(i);
                        saveToExcelUtil.writeToExcel(etName.getText().toString(), startTime, endTime, bean.getDeep(), DigitalTrans.comTime(bean.getEndTime(), bean.getStartTime()));
                    }
                }

                break;
                //插入数据
            case R.id.btn_deep:
                if (TextUtils.isEmpty(etDeep.getText().toString())) {
                    ToastUtil.showToast("输入深度不能为空！");
                    return;
                }
                double deep = Double.valueOf(etDeep.getText().toString());
                if (isStart) {
                    list.add(new DeepDataBean(startTime, DigitalTrans.formatDouble(deep) + "", etTime.getText().toString()));
                    Log.e("LIST", list.toString());
                    ToastUtil.showToast("插入数据成功");
                    Hawk.put("READDATA", list);
                    deepTime.add(DigitalTrans.getTime());

                } else {
                    ToastUtil.showToast("请先同步时间");
                }
                break;
            case R.id.btn_data_read:
                if (mBle.getConnetedDevices() != null && mBle.getConnetedDevices().size() > 0) {
                    Intent intent = new Intent();
                    intent.putExtra("FILENAME",etName.getText().toString().trim());
                    intent.setClass(this,ReadDataActivity.class);
                    startActivity(intent);
                } else {
                    ToastUtil.showToast("请先连接蓝牙设备");
                }
                break;
            //数据拟合
            case R.id.btn_fitting:
                if (Hawk.get("BLEDATA") != null && Hawk.get("READDATA") != null) {
                    data = Hawk.get("BLEDATA");
                    for (int i = 0; i < list.size(); i++) {
                        DeepDataBean bean = list.get(i);
                        for (int j = 0; j < data.size(); j++) {
                            if ((Integer.valueOf(DigitalTrans.comTime(bean.getEndTime(), bean.getStartTime()))) == Integer.valueOf(data.get(j).time) ) {
                                saveToExcelUtil.writeToExcel1(etName.getText().toString(), startTime, endTime, bean.getDeep(), DigitalTrans.comTime(bean.getEndTime(), bean.getStartTime()), data.get(j).DEV, data.get(j).AZIM);
                            }
                        }
                    }
                }
                if (Hawk.get("READDATA") != null && Hawk.get("BLEDATA") == null) {
                    for (int i = 0; i < list.size(); i++) {
                        DeepDataBean bean = list.get(i);
                        saveToExcelUtil.writeToExcel(etName.getText().toString(), startTime, endTime, bean.getDeep(), DigitalTrans.comTime(bean.getEndTime(), bean.getStartTime()));
                    }
                }

                if (Hawk.get("READDATA") == null && Hawk.get("BLEDATA") == null) {
                    ToastUtil.showToast("请先插入数据");
                }


//                saveToExcelUtil.createExcel(file1);


                break;
            //数据回访
            case R.id.btn_recovery:
                Hawk.put("deepTime",deepTime);
               startActivity(new Intent(this,ShowDataActivity.class)
               .putExtra("fileName",etName.getText().toString()));
                break;
            case R.id.iv_search:
                if (mBle.getConnetedDevices() != null && mBle.getConnetedDevices().size() > 0) {
                    AlertDialog.Builder dialog = new AlertDialog.Builder(this)
                            .setMessage("正在与蓝牙连接中，是否断开")
                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    mBle.disconnect(mBle.getConnetedDevices().get(0));
                                }
                            })
                            .setNegativeButton("取消", null);
                    dialog.create().show();
                } else {
                    startActivity(new Intent(this, BlueToothListActivity.class));
                }
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(timer!=null){
            timer.cancel();
        }

        if (mBle != null) {
            mBle.destory(getApplicationContext());
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {

        if (requestCode == 1) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            } else {
                // Permission Denied
                Toast.makeText(MainActivity.this, "Permission Denied", Toast.LENGTH_SHORT).show();
            }
            return;
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }
}
